'''
Created on 07.11.2012

@author: felix_000
'''
from game.datastructure.PentalathField import PentalathField
from game.datastructure.PlayerColor import PlayerColor
from game import GameLogic
import pickle
import os

class SaveStats:
    
    def __init__(self, field, next_player):
        self.field = field
        self.next_player = next_player
        

    


class GameServer(object):
    '''
    classdocs
    '''
    def __init__(self, player1, player2):
        '''
        Constructor
        '''
        self.field = PentalathField()
        self.moveHistory = []
        self.players = {PlayerColor.WHITE : player1, PlayerColor.BLACK : player2}
        self.nextPlayer = PlayerColor.WHITE
        self.field = PentalathField()
        self.ply = 0
        
    
    
    def save(self, field, next_player):
        f = open("gamestat", "w")
        p = pickle.Pickler(f)
        gamestat = SaveStats(field, next_player)
        p.dump(gamestat)
        f.close()
        self.saved = True
        
    def load(self):
        if os.path.isfile("gamestat"):
            f = open("gamestat", "r")
            up = pickle.Unpickler(f)
            gamestat = up.load()
            f.close()
            self.field = gamestat.field
            self.nextPlayer = gamestat.next_player

    def setValue(self, position, color):
        x,y = position
        self.field.place(color, x, y)
    
    def humanPlayerEvent(self, coordinates):
        self.players[self.nextPlayer].event(coordinates)
        
    def currentPlayer(self):
        return self.players[self.nextPlayer]
    
    def nextAction(self):
        player = self.players[self.nextPlayer]
        switchAllowed = len(self.field.history) == 1
        action = player.requestAction(self.field, self.nextPlayer, switchAllowed, self.ply)
        # moves are already checked by the players for a better performance
#        if action == GameLogic.SWAP_ACTION and switchAllowed:
#            action = self.field.history[0]
#            self.nextPlayer *= -1
#            tmp = self.players[PlayerColor.WHITE]
#            self.players[PlayerColor.WHITE] = self.players[PlayerColor.BLACK]
#            self.players[PlayerColor.BLACK] = tmp
        self.setValue(action, self.nextPlayer)
        # switch players
        oldColor = self.nextPlayer
        self.nextPlayer *= -1
        won = GameLogic.applyAction(self.field, action, oldColor)
        self.save(self.field, self.nextPlayer)
        self.ply += 1
        return won, action, oldColor

    def newGame(self):
        self.__init__(self.players[PlayerColor.WHITE], self.players[PlayerColor.BLACK])

